package dapps.web.document;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletContext;

import org.apache.commons.lang.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.apache.struts2.dispatcher.StreamResult;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.GrantedAuthority;
import org.springside.modules.orm.Page;
import org.springside.modules.security.springsecurity.SpringSecurityUtils;
import org.springside.modules.utils.DateUtils;
import org.springside.modules.web.struts2.CRUDActionSupport;

import com.opensymphony.xwork2.ActionContext;

import dapps.entity.document.Attachment;
import dapps.entity.document.Category;
import dapps.entity.document.Document;
import dapps.entity.user.User;
import dapps.service.ServiceException;
import dapps.service.document.AttachmentManager;
import dapps.service.document.CategoryManager;
import dapps.service.document.DocumentManager;

@SuppressWarnings("serial")
@Results( { @Result(name = CRUDActionSupport.RELOAD, location = "document.action?categoryid=${categoryid}&page.pageRequest=${page.pageRequest}", type = "redirect")})
public class DocumentAction extends CRUDActionSupport<Document> {

	@Autowired
	private DocumentManager documentManager;
	@Autowired
	private AttachmentManager attachmentManager;
	@Autowired
	private CategoryManager categoryManager;

	// 基本属性
	private Document entity;
	private Long id;
	private Page<Document> page = new Page<Document>(15);//每页5条记录

	private Long categoryid;  
	private Long attachmentid; 
	private String documentname;
	private List<Attachment> attachmentlist;
	private List<Category> categorylist;
	private int edit;

	// 基本属性访问函数 //

	public Document getModel() {
		return entity;
	}

	@Override
	protected void prepareModel() throws Exception {
		if (id != null) {
			entity = documentManager.get(id);			
			//categoryid = entity.getCategory().getId();
		} else {
			entity = new Document();
			entity.setPostuser(SpringSecurityUtils.getCurrentUser());
		}
	}

	public void setId(Long id) {
		this.id = id;
	}

	public Page<Document> getPage() {
		return page;
	}

	// CRUD Action 函数 //



	@Override
	public String list() throws Exception {
		List<Criterion> criterionlist = new ArrayList<Criterion>();
		if(categoryid!=null&&categoryid>0L) criterionlist.add(Restrictions.eq("category.id", categoryid));
		if(StringUtils.isNotBlank(documentname)) criterionlist.add(Restrictions.like("name", documentname,MatchMode.ANYWHERE));
		String[] alias={"postuser","postuser"};
		if(StringUtils.isBlank(page.getOrderBy())){
			page.setOrderBy("insertDate");page.setOrder("desc");
		}
		Criterion[] ca = criterionlist.toArray(new Criterion[criterionlist.size()]);
		page = documentManager.findByCriteria(page,null, ca, alias);
		return SUCCESS;
	}

	public Long getCategoryid() {
		return categoryid;
	}

	public void setCategoryid(Long categoryid) {
		this.categoryid = categoryid;
	}

	@Override
	public String input() throws Exception {
		if(edit==1&&(getAccess().equals(0L)||getAccess().equals(entity.getPostuser().getId()))) {
			edit=2;
		}
		attachmentlist = attachmentManager.getFilesByDoc(entity.getId());
		categorylist = categoryManager.getAll();
		return INPUT;
	}

	public static Long getAccess()  {
		GrantedAuthority[] authorities = SpringSecurityUtils.getCurrentUser().getAuthorities();
		int i=0;
		for (GrantedAuthority a : authorities) {
			if (a.getAuthority().equals("A_EDIT_DOCUMENT")) {
				i = 1;
			}else if (a.getAuthority().equals("A_MANAGE_DOCUMENT")) {
				i = 2;break;
			}
		}
		if(i==2)
			return 0L;
		else if(i==1)
			return SpringSecurityUtils.getCurrentUser().getId();
		return -1L;
	}

	

	@Override
	public String save() throws Exception {
		 Category c = new Category();
	        c.setId(categoryid);
	        entity.setCategory(c);        
			documentManager.save(entity);
        ServletContext servletContext = ServletActionContext.getServletContext();
        String dataDir = servletContext.getRealPath("");
        SimpleDateFormat sd = new SimpleDateFormat("yyyyMM");
        String yearmonth = sd.format(DateUtils.getCurrentDateTime()); 
        String path = "/upload"+"/"+categoryid;       
        createFolder(dataDir+ path);
        path = path+"/"+yearmonth;
        dataDir = dataDir+ path;
        createFolder(dataDir);
        if(attachment!=null){
        	for (int i=0; i < attachment.length; i++) {
                File savedFile = newFile(dataDir, attachmentFileName[i]);         
                attachment[i].renameTo(savedFile); 
                Attachment am = new  Attachment();
                am.setContentType(attachmentContentType[i]);
                am.setFileName(savedFile.getName());
                am.setPath(path+"/");
                am.setDoc(entity);
                attachmentManager.save(am);
            }
        }
       
		addActionMessage("保存文档成功");
		return RELOAD;
	}

	@Override
	public String delete() throws Exception {
		try {
			/*Document d = documentManager.get(id);
			for(Attachment a : d.getAttachments()){
				attachmentManager.delete(a);
			}*/
			Document d = documentManager.get(id);
			User u = d.getPostuser();
			if(getAccess().equals(0L)||getAccess().equals(u.getId())){
				documentManager.delete(d);	
				addActionMessage("删除文档成功");
			}else{
				addActionMessage("您没有删除权限");
			}
			
		} catch (ServiceException e) {
			logger.error(e.getMessage(), e);
			addActionMessage(e.getMessage());
		}
		return RELOAD;	
	}
	
    public InputStream getAttachmentFile() throws Exception {
    	Attachment am = attachmentManager.get(attachmentid);
    	ServletContext servletContext = ServletActionContext.getServletContext();
        String imageDirectory = servletContext.getRealPath(am.getPath());
        // retrieve default image if no file was found
        File file = new File(imageDirectory, am.getFileName());
        if (file.exists()) {
        	com.opensymphony.xwork2.Result result = ActionContext.getContext().getActionInvocation().getResult();
            if (result != null && result instanceof StreamResult) {
                StreamResult streamResult = (StreamResult) result;
                streamResult.setContentType(am.getContentType());
            }
            
            try {
                return new FileInputStream(file);
            } catch (IOException ex) {
            }
        } 
        return null;
    }
    
    private File[] attachment;
    private String[] attachmentFileName;
    private String[] attachmentContentType;

    public File[] getAttachment() {
        return attachment;
    }

    public void setAttachment(File[] attachment) {
        this.attachment = attachment;
    }

    public String[] getAttachmentFileName() {
        return attachmentFileName;
    }

    public void setAttachmentFileName(String[] attachmentFileName) {
        this.attachmentFileName = attachmentFileName;
    }

    public String[] getAttachmentContentType() {
        return attachmentContentType;
    }

    public void setAttachmentContentType(String[] attachmentContentType) {
        this.attachmentContentType = attachmentContentType;
    }

	public Long getAttachmentid() {
		return attachmentid;
	}

	public void setAttachmentid(Long attachmentid) {
		this.attachmentid = attachmentid;
	}

	public List<Attachment> getAttachmentlist() {
		return attachmentlist;
	}

	public List<Category> getCategorylist() {
		return categorylist;
	}

	public String getDocumentname() {
		return documentname;
	}

	public void setDocumentname(String documentname) {
		this.documentname = documentname;
	}

	public String createFolder(String folderPath) {
		String txt = folderPath;
		try {
			java.io.File myFilePath = new java.io.File(txt);
			txt = folderPath;
			if (!myFilePath.exists()) {
				myFilePath.mkdir();
			}
		} catch (Exception e) {			
		}
		return txt;
	}
	public File newFile(String dataDir,String name) {
		File savedFile = new File(dataDir, name);
        if(savedFile.exists()) {
        	name="1"+name;
        	savedFile = newFile(dataDir,name);
        } 
        return savedFile;
	}

	public int getEdit() {
		return edit;
	}

	public void setEdit(int edit) {
		this.edit = edit;
	}
	
}
